<template>
  <div>
    <cartTitle></cartTitle>
    <cartList
      :lists="lists"
      @delCart="delCart($event)"
      @change-num="changeNum($event)"
    ></cartList>
    <cartTotal :total="total"></cartTotal>
  </div>
</template>
<script>
import cartList from "../components/cart/cartList";
import cartTitle from "../components/cart/cartTitle";
import cartTotal from "../components/cart/cartTotal";
export default {
  components: {
    cartList,
    cartTitle,
    cartTotal
  },
  data() {
    return {
      lists: [
        {
          id: 1,
          name: "海尔冰箱505",
          price: "7999",
          num: 1
        },
        {
          id: 2,
          name: "海尔冰箱501",
          price: "5999",
          num: 1
        },
        {
          id: 3,
          name: "海尔冰箱503",
          price: "17999",
          num: 1
        },
        {
          id: 4,
          name: "海尔冰箱506",
          price: "8999",
          num: 1
        }
      ]
    };
  },
  methods: {
    delCart(id) {
      var index = this.lists.findIndex(item => {
        return item.id == id;
      });
      this.lists.splice(index, 1);
    },
    changeNum(val) {
      if (val.type == "change") {
        this.lists.some(item => {
          if (item.id == val.id) {
            item.num = val.num;
            return true;
          }
        });
      } else if (val.type == "sub") {
        this.lists.some(item => {
          if (item.id == val.id) {
            if (item.num > 1) {
              item.num--;
              return true;
            } else {
              this.delCart(item.id);
            }
          }
        });
      } else {
        this.lists.some(item => {
          if (item.id == val.id) {
            item.num++;
            return true;
          }
        });
      }
    }
  },
  computed: {
    total() {
      let total = 0;
      this.lists.forEach(item => {
        total += item.price * item.num;
      });
      return total;
    }
  }
};
</script>
<style lang=""></style>
